<template>
  <div class="transaction-add">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>手动添加交易记录</span>
        </div>
      </template>

      <el-form
        ref="transactionForm"
        :model="transactionForm"
        :rules="rules"
        label-width="120px"
        style="max-width: 800px;"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="支付平台" prop="paymentPlatform">
              <el-radio-group v-model="transactionForm.paymentPlatform">
                <el-radio :label="1">微信</el-radio>
                <el-radio :label="2">支付宝</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="交易时间" prop="transactionTime">
              <el-date-picker
                v-model="transactionForm.transactionTime"
                type="datetime"
                placeholder="选择交易时间"
                style="width: 100%;"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="交易分类" prop="transactionCategory">
              <el-input
                v-model="transactionForm.transactionCategory"
                placeholder="请输入交易分类"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="交易对方" prop="transactionPartner">
              <el-input
                v-model="transactionForm.transactionPartner"
                placeholder="请输入交易对方"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="对方账号" prop="partnerAccount">
              <el-input
                v-model="transactionForm.partnerAccount"
                placeholder="请输入对方账号"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品说明" prop="productDescription">
              <el-input
                v-model="transactionForm.productDescription"
                placeholder="请输入商品说明"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="收支类型" prop="incomeExpense">
              <el-select v-model="transactionForm.incomeExpense" placeholder="请选择收支类型">
                <el-option label="收入" :value="1"></el-option>
                <el-option label="支出" :value="2"></el-option>
                <el-option label="不计收支" :value="3"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="金额" prop="amount">
              <el-input
                v-model.number="transactionForm.amount"
                placeholder="请输入金额"
                type="number"
                :min="0"
                :step="0.01"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="收/付款方式" prop="paymentMethod">
              <el-input
                v-model="transactionForm.paymentMethod"
                placeholder="请输入收/付款方式"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="交易状态" prop="transactionStatus">
              <el-input
                v-model="transactionForm.transactionStatus"
                placeholder="请输入交易状态"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="交易订单号" prop="transactionOrderNumber">
              <el-input
                v-model="transactionForm.transactionOrderNumber"
                placeholder="请输入交易订单号"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商家订单号" prop="merchantOrderNumber">
              <el-input
                v-model="transactionForm.merchantOrderNumber"
                placeholder="请输入商家订单号"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="备注">
          <el-input
            v-model="transactionForm.remarks"
            placeholder="请输入备注信息"
            type="textarea"
            :rows="3"
          ></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm">提交</el-button>
          <el-button @click="resetForm">重置</el-button>
          <el-button @click="goBack">返回列表</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { transactionService } from '@/api/transactionService'

export default {
  name: 'TransactionAdd',
  data() {
    return {
      transactionForm: {
        paymentPlatform: 1,
        transactionTime: new Date(),
        transactionCategory: '',
        transactionPartner: '',
        partnerAccount: '',
        productDescription: '',
        incomeExpense: 2,
        amount: 0,
        paymentMethod: '',
        transactionStatus: '成功',
        transactionOrderNumber: '',
        merchantOrderNumber: '',
        remarks: ''
      },
      rules: {
        paymentPlatform: [
          { required: true, message: '请选择支付平台', trigger: 'change' }
        ],
        transactionTime: [
          { required: true, message: '请选择交易时间', trigger: 'change' }
        ],
        transactionPartner: [
          { required: true, message: '请输入交易对方', trigger: 'blur' }
        ],
        incomeExpense: [
          { required: true, message: '请选择收支类型', trigger: 'change' }
        ],
        amount: [
          { required: true, message: '请输入金额', trigger: 'blur' },
          { type: 'number', min: 0, message: '金额必须大于等于0', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    formatDate(dateString) {
      if (!dateString) return ''
      // 创建Date对象，解析UTC时间
      const date = new Date(dateString)
      
      // 获取UTC时间的各个部分并加上8小时（转换为UTC+8）
      let year = date.getUTCFullYear()
      let month = date.getUTCMonth() + 1
      let day = date.getUTCDate()
      let hours = date.getUTCHours() + 8
      let minutes = date.getUTCMinutes()
      let seconds = date.getUTCSeconds()
      
      // 处理小时可能超过24的情况
      if (hours >= 24) {
        hours -= 24
        // 创建一个新的日期对象来处理日期变更
        const tempDate = new Date(Date.UTC(year, month - 1, day))
        tempDate.setDate(tempDate.getDate() + 1)
        year = tempDate.getUTCFullYear()
        month = tempDate.getUTCMonth() + 1
        day = tempDate.getUTCDate()
      }
      
      // 格式化输出
      return `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')} ${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`
    },
    submitForm() {
      this.$refs.transactionForm.validate((valid) => {
        if (valid) {
          // 转换日期格式
          const formData = {
            ...this.transactionForm,
            transactionTime: this.transactionForm.transactionTime ? this.formatDate(this.transactionForm.transactionTime) : null
          }
          
          transactionService.createTransaction(formData)
            .then(() => {
              this.$message.success('交易记录添加成功！')
              this.$router.push('/transaction-list')
            })
            .catch(error => {
              this.$message.error('添加失败，请重试')
              console.error(error)
            })
        } else {
          this.$message.error('表单验证失败，请检查必填项')
          return false
        }
      })
    },
    resetForm() {
      this.$refs.transactionForm.resetFields()
      this.transactionForm.transactionTime = new Date()
    },
    goBack() {
      this.$router.push('/transaction-list')
    }
  }
}
</script>

<style scoped>
.transaction-add {
  padding: 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.el-form {
  margin-top: 20px;
}

.el-button + .el-button {
  margin-left: 10px;
}
</style>